import asyncio
import sys
import os
import time
import re
from datetime import datetime, timedelta

# 添加项目根目录到Python路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from crypto.crypto_analyzer_strategies import CryptoAnalyzer
from main02 import DingTalkRobot

class TradingSimulator:
    def __init__(self):
        self.trade_records = []  # 记录交易记录
        self.last_send_time = {}  # 记录最后发送时间
        self.win_count = 0  # 胜利次数
        self.total_count = 0  # 总交易次数
    
    def parse_trend_and_price(self, message):
        """从消息中解析趋势方向和当前价格"""
        # 解析趋势方向
        trend_match = re.search(r'趋势判断\n(.+?)\(', message)
        if trend_match:
            trend_text = trend_match.group(1)
            if '看涨' in trend_text:
                direction = 'up'
            elif '看跌' in trend_text:
                direction = 'down'
            else:
                direction = 'neutral'
        else:
            direction = 'neutral'
        
        # 解析当前价格
        price_match = re.search(r'当前价格: \$(\d+\.\d+)', message)
        if price_match:
            current_price = float(price_match.group(1))
        else:
            current_price = None
        
        return direction, current_price
    
    def record_trade(self, direction, current_price, message, symbol='BTCUSDT'):
        """记录交易信息"""
        trade_time = datetime.now()
        trade_record = {
            'time': trade_time,
            'direction': direction,
            'entry_price': current_price,
            'message': message,
            'symbol': symbol,
            'verified': False
        }
        self.trade_records.append(trade_record)
        print(f"记录交易: {direction} @ {current_price}, 时间: {trade_time}")
        return trade_record
    
    def verify_trades(self, analyzer):
        """验证10分钟前的交易结果"""
        current_time = datetime.now()
        verified_count = 0
        
        for trade in self.trade_records:
            if trade['verified'] or current_time - trade['time'] < timedelta(minutes=10):
                continue
            
            # 获取10分钟后的价格数据
            symbol = trade['symbol']
            historical_data = analyzer.historical_data.get(symbol, {}).get('1m', [])
            
            if not historical_data:
                continue
            
            # 找到交易时间后的价格
            entry_price = trade['entry_price']
            exit_price = None
            
            for candle in historical_data:
                candle_time = datetime.fromtimestamp(candle['time'])
                if candle_time >= trade['time'] + timedelta(minutes=10):
                    exit_price = candle['close']
                    break
            
            if exit_price is None and historical_data:
                # 如果没有找到10分钟后的数据，使用最新的数据
                exit_price = historical_data[-1]['close']
            
            if exit_price is not None:
                # 判断交易结果
                if trade['direction'] == 'up':
                    win = exit_price > entry_price
                elif trade['direction'] == 'down':
                    win = exit_price < entry_price
                else:
                    win = None
                
                if win is not None:
                    self.total_count += 1
                    if win:
                        self.win_count += 1
                    
                    trade['verified'] = True
                    trade['exit_price'] = exit_price
                    trade['win'] = win
                    
                    win_rate = (self.win_count / self.total_count * 100) if self.total_count > 0 else 0
                    print(f"交易验证: {trade['direction']} 入场:{entry_price} 出场:{exit_price} {'胜' if win else '负'} 胜率: {win_rate:.1f}%")
                    verified_count += 1
        
        return verified_count
    
    def can_send_message(self, symbol='BTCUSDT'):
        """检查是否可以发送消息（10分钟限制）"""
        current_time = datetime.now()
        last_time = self.last_send_time.get(symbol)
        
        if last_time is None or current_time - last_time >= timedelta(minutes=10):
            self.last_send_time[symbol] = current_time
            return True
        
        return False
    
    def get_statistics(self):
        """获取交易统计信息"""
        if self.total_count == 0:
            return "暂无交易记录"
        
        win_rate = (self.win_count / self.total_count * 100)
        return f"总交易: {self.total_count}次, 胜利: {self.win_count}次, 胜率: {win_rate:.1f}%"

def send_analysis_periodically(robot, access_token, secret):
    """定期执行分析并发送结果到钉钉"""
    analyzer = CryptoAnalyzer()
    simulator = TradingSimulator()
    print("开始执行分析...")    
    
    while True:
        try:
            # 执行分析
            results = asyncio.run(analyzer.start_analysis('1m'))
            
            # 验证之前的交易
            simulator.verify_trades(analyzer)
            
            # 发送每个结果到钉钉
            for result in results:
                # 检查是否包含neutral信号，如果是则跳过发送
                if 'neutral' in result or '横盘' in result:
                    print("检测到neutral信号，跳过发送")
                    continue
                
                # 解析趋势和价格
                direction, current_price = simulator.parse_trend_and_price(result)
                
                # 检查是否可以发送消息（10分钟限制）
                if not simulator.can_send_message():
                    print("10分钟内已发送过消息，跳过本次发送")
                    continue
                
                # 记录交易
                if direction != 'neutral' and current_price is not None:
                    simulator.record_trade(direction, current_price, result)
                
                # 发送消息到钉钉
                message = f"市场分析结果:\n\n{result}"
                if simulator.total_count > 0:
                    stats = simulator.get_statistics()
                    message += f"\n\n=== 模拟交易统计 ===\n{stats}"
                
                robot.send_message(message)
                print(f"发送消息到钉钉，趋势: {direction}, 价格: {current_price}")
                
                time.sleep(1)  # 避免发送过快
            
            # 等待60秒
            time.sleep(60)
        except Exception as e:
            print(f"发送分析结果时出错: {e}")
            time.sleep(60)

def main():
    # 配置钉钉机器人参数
    access_token = "812b3e73ff794d5b5d46f708214f82fb1fd00622dfd2a7eba7ca93c1be9f6ecb"  # 替换为实际的access_token
    secret = "SECcdd18d9a38d78c997d9441d289f7159a03a1d6dd5f8652c50f66e68aaff54fa2"  # 替换为实际的secret
    
    # 创建钉钉机器人实例
    robot = DingTalkRobot(access_token, secret)
    
    # 开始定期发送分析结果
    send_analysis_periodically(robot, access_token, secret)

if __name__ == "__main__":
    main()